<?php
namespace Admin\Controller;
use Think\Controller;
/**
 * 计划任务部分
 * @author Lain
 *
 */
class CronController extends Controller {
	
	public function test(){
		$data['create_time'] = NOW_TIME;
		$result = M('post_log')->add($data);
	}
	
	//获取一篇文章内容
	public function getArticleDetail(){
	    $map['status'] = 0;
	    $detail = M('Article')->where($map)->order('id DESC')->field('id')->find();
	    if($detail){
	        $result = D('Admin/Article')->getDetail($detail['id']);
	        exit('success');
	    }else{
	        exit('over');
	    }
	    
	}
	
	//tuicool
	public function tuicool(){
	    //获取catid, 及其对应的站点code
		if(!I('get.catid')){
			$map_cron['next_cron_time'] = array('lt', NOW_TIME);
			$map_cron['cron'] = 1;
			$detail = M('ArticleCategory')->where($map_cron)->order('next_cron_time')->find();
			
			$catid = $detail['catid'];
			
			//如果没有计划, 返回真
			if(!$detail)
				exit('over');
			
			//更新此次更新时间
			$data_cron['last_cron_time'] = NOW_TIME;
			$data_cron['next_cron_time'] = NOW_TIME + 600;		//下次时间 1小时
			

			$url = $this->getTuicoolApi($detail['setting']);
		}else{
			//测试部分
			$catid = I('get.catid');
			$detail = M('ArticleCategory')->where(array('catid' => $catid))->find();
			$url = $this->getTuicoolApi($detail['setting']);
		}
		//总用时
		$total_time = new \Lain\Ctimer;
		$total_time->start();

		//爬取用时
		$snoopy_time = new \Lain\Ctimer;
		$snoopy_time->start();
		//使用snoopy
		$snoopy = new \Lain\Snoopy;
		$snoopy->rawheaders["COOKIE"] = "_tuicool_session=BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJWI1ZjE1ODdiNzAwNGJmNGMyOTI4Mzg1MzQyNzhjYjA5BjsAVEkiEF9jc3JmX3Rva2VuBjsARkkiMWl5R0ZmRWgvVnBRRVFKU3NMcU41TlU0MXFPcTRZK2Z2RGYzakhpWDBlZFE9BjsARkkiDHVzZXJfaWQGOwBGaQNdygE%3D--3a725574e328856228f2104de32c43130995049f; domain=.tuicool.com; path=/; expires=Wed, 05-Jun-2019 07:43:24 GMT; HttpOnly";
		$snoopy->rawheaders["Pragma"] = "no-cache";
		//代理
	    // $snoopy->proxy_host = S('proxy_host');
	    // $snoopy->proxy_port = S('proxy_port');
	    
		$snoopy->fetch($url);
		$content = json_decode($snoopy->results, true);

		$snoopy_time->stop();
		if(!$content || $content['success'] != true){
		    //设置当前代理
		    // D('Proxy')->loseConnect(S('proxy_host'), S('proxy_port'));
		    exit('error');
		}else{
		  // D('Proxy')->successConnect(S('proxy_host'), S('proxy_port'));
		}

		// 获取成功后, 更新下次执行时间
		$result = M('ArticleCategory')->where('catid='.$catid)->save($data_cron);

		//文章操作时间
		$article_time = new \Lain\Ctimer;
		$article_time->start();
		//循环文章
		$success_article_add = 0;
		//获取code相关文章
		if($content['articles']){
			foreach ($content['articles'] as $key => $value) {
				$codes .= $codes ? ','.$value['id'] : $value['id'];
			}
			$exist_map['code'] = array('in', $codes);
			$exist_article = M('article')->where($exist_map)->index('code')->field('id,code')->select();
		}

		foreach ($content['articles'] as $article){
		    //查看文章是否存在
		    // $exist = M('Article')->where(array('code' => $article['id']))->find();
		    if(array_key_exists($article['id'], $exist_article))
		        continue;
		    $success_article_add ++;
		    //保存文章
		    $data['catid'] 			= $catid;
		    $data['code'] 			= $article['id'];   //tuicool唯一吗
		    $data['title'] 			= $article['title'];
		    $data['url'] 			= $article['url'];
		    $data['description'] 	= $article['abs'];
		    $data['thumb'] 			= $article['img'];
		    $data['inputtime'] 		= $data['updatetime'] = NOW_TIME;
		    $data['status'] 		= 0;
		    D('Article')->add_content($data);
		}

		$article_time->stop();
		$total_time->stop();
		if(I('get.catid')){
			echo '总用时'.$total_time->elapsed().'<br>';
			echo 'snoopy爬取时间'.$snoopy_time->elapsed().'<br>';
			echo '文章循环插入时间'.$article_time->elapsed().'<br>';
			echo '成功插入'.$success_article_add.'条<br>';
		}
		
		exit('success');
	    
	}
	
	//获取一个代理IP, 10分钟跑一次
	public function proxy(){
	    
	    $cron_data = D('Proxy')->getCron();
	    if($cron_data && $cron_data['next_cron_time'] > NOW_TIME){
	        //不需要执行
	        die('over');
	    }
	    
	    //检测一个代理是否可用, 如果可用则下一次执行时间为1小时//如果不可用, 不更改下一次执行时间
	    if(D('Proxy')->getWebProxy()){
	        D('Proxy')->updateCron(1);
	        die('success');
	    }else{
	        D('Proxy')->updateCron();
	        die('error');
	    }
	    
	}

	public function refreshProxy(){
		//刷新代理列表
		D('Proxy')->delete();
		if(D('Proxy')->getWebProxy()){
	        D('Proxy')->updateCron(1);
	        die('success');
	    }else{
	        D('Proxy')->updateCron();
	        die('error');
	    }
	}
	
	//每分钟跑一次
	public function gather(){
		//保存请求时间
		//$data['create_time'] = NOW_TIME;
		//$result = M('post_log')->add($data);
		//取出需要更新文章
		
		$map_cron['next_cron_time'] = array('lt', NOW_TIME);
		//$map_cron['status']		//是否在连载
		$detail = D('Book')->where($map_cron)->order('next_cron_time')->find();

		$gid = $detail['gid'];
		$bookid = $detail['id'];
		
		//如果没有计划, 返回真
		if(!$detail)
			exit('over');
		
		//更新此次更新时间
		$data_cron['last_cron_time'] = NOW_TIME;
		$data_cron['next_cron_time'] = NOW_TIME + 3600;		//下次时间 1小时
		
		$result = D('Book')->where('id='.$bookid)->save($data_cron);
		
		if(!$gid)
			exit('error');
		
		$url = $this->getBookJs($gid);
		
		$content = json_decode(\Org\Net\Http::fsockopenDownload($url), true);
		
		if(!$content || $content['status'] != 1){
			exit('error');
		}
		//判断是否采集过, 没有的话, 保存文章信息
		//判断最新章节
		//取出所有章节
		$group = $content['data']['group'];
		$map['bookid'] = $data['bookid'] = $bookid;
		
		//待优化: 查看已采集的章节数量,
		$count_chapter = D('BookChapter')->where('bookid='.$bookid)->count();
		if($count_chapter < count($group)){
			foreach ($group as $k => $chapter){
					
				if($k < $count_chapter)
					continue;
				//判断是否已经存在
				$map['chapterid'] = $chapter['index'];
				$exist_chapter = D('BookChapter')->where($map)->field('id, status')->find();
				if(!$exist_chapter){
					//保存
					$data['chapterid'] = $chapter['index'];
					$data['cid'] = $chapter['cid'];
					$data['index'] = $chapter['index'];
					$data['rank'] = $chapter['rank'];
					$data['title'] = $chapter['text'];
					$data['url'] = $chapter['href'];
						
					D('BookChapter')->add($data);
				}
			}
				
			//更新最后一章信息到Book表
			$last_chapter['last_chapter_title'] = $data['title'];
			$last_chapter['last_chapter_index'] = $data['index'];
			$last_chapter['last_chapter_update_time'] = NOW_TIME;
			D('Book')->where('id='.$bookid)->save($last_chapter);
			exit('success');
		}else{
			//更新下一个任务
			$this->gather();
		}
		
		//更新, 记录信息
	}
	
	//返回形如 http://m.baidu.com/tc?srd=1&appui=alaxs&ajax=1&gid=3961103225
	public function getBookJs($gid){
		//没有gid字段, 返回错误
		if(!$gid)
			return false;
		 
		$new_url = 'http://m.baidu.com/tc?srd=1&appui=alaxs&ajax=1&gid='.$gid;
		return $new_url;
	}
	
	public function getTuicoolApi($site){
		//没有gid字段, 返回错误
		if(!$site)
			return false;
		 
		$new_url = 'https://www.tuicool.com'.$site.'&pn=0&m=1&0=0';
		return $new_url;
	}

	//推送文章给用户
	public function inoreader(){
		//取出最近的一个用户
		$map['updatetime'] = array('lt', NOW_TIME - 60*30);
		$cron_detail = M('UserArticleCategoryCron')->where($map)->order('updatetime')->find();
		if(empty($cron_detail)){
			echo 'over';exit;
		}
		D('Home/User')->pushArticleByCatid($cron_detail['userid'], $cron_detail['catid']);
		//更新任务执行时间
		$update_info['updatetime'] = NOW_TIME;
		M('UserArticleCategoryCron')->where(['cronid' => $cron_detail['cronid']])->save($update_info);
	}
	
	//向百度推送文章页面
	public function pushSitemap(){
	    //取未推送成功的20篇文章
	    $pagesize = 20;
	    $map['pushed'] = array('neq', 1);
	    $article_list = M('Article')->where($map)->field('id')->order('id')->limit($pagesize)->select();
	    if(!$article_list){
	        echo 'over!';exit;
	    }
	    
	    foreach ($article_list as $article){
	        $urls[] = 'http://www.pdosgk.com/index.php/Home/News/show/id/'.$article['id'].'.html';
	    }
	    /* $urls = array(
	            'http://www.example.com/1.html',
	            'http://www.example.com/2.html',
	    ); */
	    $api = 'http://data.zz.baidu.com/urls?site=www.pdosgk.com&token=t6aytxSiZHWx609R';
	    $ch = curl_init();
	    $options =  array(
	            CURLOPT_URL => $api,
	            CURLOPT_POST => true,
	            CURLOPT_RETURNTRANSFER => true,
	            CURLOPT_POSTFIELDS => implode("\n", $urls),
	            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
	    );
	    curl_setopt_array($ch, $options);
	    $result = json_decode(curl_exec($ch), true);
	    $info['pushed'] = 1;
	    if($result['success'] == count($urls)){
	        foreach ($article_list as $article){
	            M('Article')->where(array('id' => $article['id']))->save($info);
	        }
	    }
	    var_dump($result);
	}


    public function pushArticleById(){
        $id = I('get.id');
        
        return D('Home/User')->pushArticleById($id);
    }

}